package org.red5.audio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Convert FLV to MP3
 */
public class FlvToMp3AudioConverter extends AudioConverter {

	public FlvToMp3AudioConverter(String sourceFile, String destinationDirectory, String newFileName) {
		this(new AudioSettings(), sourceFile, destinationDirectory, newFileName, false);
	}

	public FlvToMp3AudioConverter(AudioSettings audioSettings,
			String sourceFile, String destinationDirectory, String newFileName, boolean deleteSourceFile) {
		super(audioSettings, sourceFile, destinationDirectory, newFileName, deleteSourceFile);
	}

	protected void performConvertion() throws RuntimeException
	{
		String command = "ffmpeg -i " + getSourceFile() + " -ar "
		+ getAudioSettings().getSampleRate() + " -ab "
		+ getAudioSettings().getBitRate() + "k -ac "
		+ getAudioSettings().getChannels() + " -vn -y -f mp3 " + (getDestinationDirectory() + getNewFileName());
		
		
		Process p;
		try {
			p = Runtime.getRuntime().exec(command);
//			int retVal = 0;
//			boolean finish = false;
//			while( !finish ){
//				try{
//					retVal = p.exitValue();
//					finish = true;
//				} catch(IllegalThreadStateException e){
//					try {
//						Thread.sleep(10);
//					} catch (InterruptedException e2) {}
//				}
//			}
			
			BufferedReader stdError = new BufferedReader(new InputStreamReader(
					p.getErrorStream()));
			
			// read any errors from the attempted command
			String error = null;
			while ((error = stdError.readLine()) != null) {
				error += error; 
			}
			if(error != null) 
			{
				throw new RuntimeException("Dos command error: \n" + error);
			}
		} catch (IOException e) {
			throw new RuntimeException("Error reading from stderror");
		} 
	}
}
